package com.onekbase.demo.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class TcpServerAioDemo {
    public static void main(String[] args) throws IOException {
        AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress("localhost", 8084);
        serverSocket.bind(address);
        serverSocket.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
                serverSocket.accept(null, this); // 接受下一个连接
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer buffer) {
                        buffer.flip();
                        String message = new String(buffer.array(), 0, result);
                        System.out.println("接收到消息: " + message);
                        // 将消息回显给客户端
                        socketChannel.write(ByteBuffer.wrap(message.getBytes()));
                        buffer.clear();
                    }
                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        System.out.println("错误: " + exc.getMessage());
                    }
                });
            }
            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("错误: " + exc.getMessage());
            }
        });
        // 保持程序运行
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
